package com.smile.cloud.aopConfig.config;

import cn.hutool.core.util.StrUtil;
import com.smile.cloud.aopConfig.filter.LogTraceRequestFilter;
import com.smile.cloud.common.base.constant.CommonConstant;
import feign.RequestInterceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @author LGC
 */
@Configuration
public class InterceptorConfig {

    @Bean
    public FilterRegistrationBean<LogTraceRequestFilter> logTraceRequestFilter() {
        FilterRegistrationBean<LogTraceRequestFilter> filterRegBean = new FilterRegistrationBean<>();
        filterRegBean.setFilter(new LogTraceRequestFilter());
        filterRegBean.addUrlPatterns("/*");
        filterRegBean.setOrder(Ordered.LOWEST_PRECEDENCE - 1);



        return filterRegBean;
    }

    /**
     * 所有feign请求,header 加参数
     *
     * @return
     */
    @Bean
    public RequestInterceptor httpFeignInterceptor() {

        return template -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();

                String traceId = request.getHeader(CommonConstant.TRACE_ID_HEADER);
                if (StrUtil.isNotBlank(traceId)) {
                    template.header(CommonConstant.TRACE_ID_HEADER, traceId);
                }
               /* Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    String headerName;
                    String headerValue;
                    while (headerNames.hasMoreElements()) {
                        headerName = headerNames.nextElement();
                        if (CommonConstant.TRACE_ID_HEADER.contains(headerName)) {
                            headerValue = request.getHeader(headerName);
                            template.header(headerName, headerValue);
                        }
                    }
                }*/
            }
        };
    }

}
